<template>
  <div class="app-container">
    <div class="container" >
      <a-card>
        
        <title-name title="标准WBS模板"></title-name>
        <div class="button-bar">
          <!--          <a-button type="primary" @click="action('undo')">保存信息</a-button>-->
          <!-- <a-button type="default" @click="action('undo')">回撤</a-button>
          <a-button type="default" @click="action('redo')">重做</a-button> -->
          <!--        <a-button type="primary" @click="importFromTemplate()">导入模板</a-button>-->
          <a-button type="primary" @click="addModal()">新增节点</a-button>
          <a-button type="default" @click="action('moveUp')">上移</a-button>
          <a-button type="default" @click="action('moveDown')">下移</a-button>
          <a-button type="default" @click="action('outdent')">升级</a-button>
          <a-button type="default" @click="action('indent')">降级</a-button>
          <!--          <a-button type="default" @click="action('undo')">回撤</a-button>-->
          <a-button type="default" @click="action('del')">删除节点</a-button>
          <!-- <a-button type="primary" @click="action('moveBackward')">减一天</a-button>
          <a-button type="primary" @click="action('moveForward')">加一天</a-button>
          <a-button type="primary" @click='exportToPDFs'>下载PDF</a-button> -->
          <!-- <a-button type="primary" @click="showDrawer()">查看甘特图</a-button> -->
        </div>
        <div class="gantt-layout">
          <a-drawer
                  title=""
                  placement="right"
                  :closable="false"
                  :z-index="10"
                  :get-container="false"
                  :visible="visible"
                  :body-style="{padding:'0'}"
                  :wrap-style="{ position: 'absolute'}"
                  width="50%"
                  :after-visible-change="afterVisibleChange"
                  @close="onClose"
          ><gantt ref="ganttCom" class="left-container"
                  :columns="ganttColumns"
                  :plugins="plugins"
                  :tasks="tasks"
                  :height="661"
                  @task-deleted="deleteTask"
                  @task-updated="logTaskUpdate"
                  @link-updated="logLinkUpdate"
                  @task-addModal="addModal"
                  @task-selected="selectTask"></gantt>
          </a-drawer>
          <a-table row-key="nodeId" :scroll="{ x: 800, y: 600 }"
                   :columns="columns"
                   :defaultExpandAllRows="true"
                   :pagination="false"
                   :expandIconColumnIndex="1"
                   @expand="rowExpand"
                   :data-source="tableData"
                   :rowClassName="rowClassNames"
                   :customRow="clickRow">
            <!--阶段/类别-->
            <template slot="name" slot-scope="text, record" >
              <div style="display: inline-block">
                <!-- <cell @change="changeName" placeholder="请输入" @blur="blurData" :value="record.name"></cell> -->
                <BaseInput  @change="changeName" placeholder="请输入" @blur="blurData" :value="record.name"></BaseInput>
              </div>
            </template>
            
            <!-- 管控级别 -->
            <template  slot="level" slot-scope="text, record" >
              <!--                    <cell :ref="`countryCode_${record.key}`" formType="select"    :value="text" :text="text" >-->
              <a-select v-if="record.nodeLevel=='3'" :defaultValue="nodeList[0].controlLevelId" aria-placeholder="请选择" :value="record.controlLevelName"  @change="changeLevel"  style="width:80px">
                <a-select-option v-for="item in nodeList" :key="item.controlLevelId">{{item.controlLevelName}}</a-select-option>
              </a-select>
            </template>
            <!-- 周期 -->
            <template slot="duration" slot-scope="text, record">
              <BaseInputNumber placeholder="请输入" v-if="record.nodeLevel=='3'"   :value="record.duration" :min="0" :max="2000"  @blur="editduration" />
              <span v-else>{{record.duration}}</span>
            </template>
            <!-- 标准开始时间 -->
            <template slot="startDate" slot-scope="text, record">
              <BaseInputNumber placeholder="请输入" v-if="record.nodeLevel=='3'"  :value="record.startDate"  :min="0" :max="2000"  @blur="editstartDate" />
            </template>
            
            <!-- 时间标准 -->
            <template slot="dateStandard" slot-scope="text, record">
              <a-select v-if="record.nodeLevel=='3'" aria-placeholder="请选择" v-model="record.dateStandardName"  @change="changedateStandard"  style="width:80px">
                <a-select-option value="1" >
                  开工日前
                </a-select-option>
                <a-select-option value="0">
                  开工日后
                </a-select-option>
              </a-select>
            </template>
            <!-- 标准完成时间 -->
            <template slot="completeDate" slot-scope="text, record">
              <span v-if="record.completeDate<0">开工日前{{Math.abs(record.completeDate)}}天</span>
              <span v-if="record.completeDate>0">开工日后{{record.completeDate}}天</span>
            </template>
            <!-- 完成标准 -->
            <template slot="completeStandard" slot-scope="text, record">
              <BaseInput v-if="record.nodeLevel=='3'" @blur="changecompleteStandard" placeholder="请输入" v-model="record.completeStandard"></BaseInput>
            </template>
            <!-- 验证资料 -->
            <template slot="verifyDoc" slot-scope="text, record">
              <BaseInput v-if="record.nodeLevel=='3'" @blur="changeverifyDoc" placeholder="请输入" v-model="record.verifyDoc"></BaseInput>
            </template>
            <!-- 第一责任人 -->
            <template slot="firstResponsible" slot-scope="text, record">
              <a-select style="width:200px" v-model="record.firstResponsible" placeholder="请选择" @focus="selectfirstRes" @change="changeFirstRes">
                <a-select-option v-for='item in firstResponsible' :key="item.id" :value="item.id">{{item.name}}</a-select-option>
              </a-select>
            </template>
          
          </a-table>
        </div>
        <a-modal
                :visible="addVisible"
                ok-text="确 定 新 增"
                cancel-text="取 消"
                title="新增节点"
                :confirm-loading="confirmLoading"
                @ok="handleSubmit"
                @cancel="handleCancel">
          <!--          <a-form>-->
          <!--            <div>-->
          <!--              -->
          <!--            <div style="width:100%;height:60px;background-color:#349ED8" >-->
          <!--                <div style="line-height:60px;color:#fff;font-weight:bold;font-size:16px"> 新增节点</div>-->
          <!--            </div>-->
          <!--            <a-form-item label="新增节点位置" style="display:flex;margin:20px 0">-->
          <!--              <a-select v-model="levelOption" style="width:200px" placeholder="请选择节点位置">-->
          <!--                <a-select-option label="同等级" value="1">同等级</a-select-option>-->
          <!--                <a-select-option label="下级" value="0">下级</a-select-option>-->
          <!--              </a-select>-->
          <!--            </a-form-item>-->
          <!--            </div>-->
          
          <!--          </a-form>  -->
          <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }" >
            <!--                          <div style="width:100%;height:60px;background-color:#349ED8" >-->
            <!--                              <div style="line-height:60px;color:#fff;font-weight:bold;font-size:16px"> 新增节点</div>-->
            <!--                          </div>-->
            <a-form-item label="新增节点位置">
              <a-select
                      v-decorator="['note', { rules: [{ required: true, message: '请选择节点位置' }] }]"
                      placeholder="请选择节点位置"
                      @change="handleSelectChange">
                <a-select-option value="1">
                  同等级
                </a-select-option>
                <!--                <a-select-option value="2" v-if="selectedData.nodeLevel==3" disabled>-->
                <!--                    下级-->
                <!--                </a-select-option>-->
                <a-select-option  value="2" >
                  下级
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-modal>
      </a-card>
    </div>
    <task-template-modal @hide="importFromTemplateHide" @dataImport="onTemplateDataImport" :selectLevel="selectLevel"
                         :visible="taskTemplateVisible" />
  </div>
</template>
<script>
  import { gantt } from 'dhtmlx-gantt'
  import { getWbsTemplate, addSameNode, addNextNode, editNode, deleteNode ,editTemplateNode, getNodeControl} from '@/api/template'
  import Gantt from '../gantt/gantt'
  import TaskTemplateModal from '../gantt/template-modal'
  import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
  import * as moment from 'moment'
  import EditableCell from './EditableCell'
  import { getOrgPost } from '@/api/commons'
  // import Cell from './cell'
  export default {
    name: 'DhtmlxGantt',
    components: { Gantt, TaskTemplateModal ,EditableCell},
    data() {
      return {
        levelOption:'',
        tableData: [],
        startDates:'',
        type:'',
        locale,
        tasks: { data: [], links: [] },
        columns: [],
        templateId:'',
        addLevel:'',
        rowSelection: {},
        resultData:{},
        saveSelectRows:[],
        ganttColumns:[],
        firstResponsible:[],
        preTasks: [],
        selectLevel:'',
        taskType: 'task',
        modalTitle: '新增节点',
        confirmLoading: false,
        nodeList:'',
        addVisible: false,
        visible:false,
        selectId:'',
        taskTemplateVisible: false,
        plugins: {
          undo: true,
          drag_timeline: true
        },
        messages: [],
        selectedTask: null,
        rangeConfig: {
          rules: [{ type: 'array', required: true, message: '请选择计划日期!' }]
        }
      }
    },
    beforeCreate() {
      this.form = this.$form.createForm(this, {})
    },
    beforeUpdate() {
      this.columns = this.getColumns()
    },
    created() {
      this.templateId = this.$route.query.wbsTemplateId
      console.log(this.templateId)
      this.getWbsTemplate()
      this.getNodeControl()
      localStorage.removeItem('task')
      localStorage.removeItem('link')
      this.rowSelection = this.getRowSelection()
      this.columns = this.getColumns()
      this.tasks.data = []
      this.tasks.links = []
      this.ganttColumns = [
        {
          name: 'sortNum', label: '序号', align: 'center',tree: true, width: 0, template: function(obj) {
            console.log(obj)
            return obj.$index + 1
          }
        }
      ]
    },
    mounted: function() {
      this.columns = this.getColumns()
    },
    methods: {
      changeFirstRes(value){
        console.log(value)
        let data={
          templateId:this.templateId,
          nodeId:this.selectedData.nodeId,
          firstResponsible:value
        }
        console.log(data)
        editTemplateNode(data).then((res)=>{
          if(res){
            this.getWbsTemplate()
          }
          if(res.code=='200'){
            this.$message.success("修改成功")
          }
        })
      },
      selectfirstRes(){
        this.getOrgPost()
      },
      // 第一负责人
      getOrgPost(){
        getOrgPost().then((res)=>{
          this.firstResponsible = res.data
        })
      },
      getNodeControl(){
        getNodeControl().then((res)=>{
          this.nodeList = res.data
          console.log(res)
        })
      },
      changeName(value){
        console.log(value)
      },
      // 标准开始时间
      editstartDate(e){
        console.log(e.target.value)
        this.saveSelectRows.startDate = e.target.value;
        let startDate = this.saveSelectRows.startDate
        if(!startDate){
          startDate = 0
        }
        let data={
          templateId:this.templateId,
          nodeId:this.selectedData.nodeId,
          startDate:startDate
        }
        console.log(data)
        editTemplateNode(data).then((res)=>{
          if(res){
            this.getWbsTemplate()
          }
          if(res.code=='200'){
            this.$message.success("修改成功")
          }
        })
      },
      // 周期
      editduration(e){
        console.log(e.target.value)
        this.saveSelectRows.duration = e.target.value;
        let duration = this.saveSelectRows.duration
        if(!duration){
          duration = 0
        }
        let data={
          templateId:this.templateId,
          nodeId:this.selectedData.nodeId,
          duration:duration
        }
        console.log(data)
        editTemplateNode(data).then((res)=>{
          if(res){
            this.getWbsTemplate()
          }
          if(res.code=='200'){
            this.$message.success("修改成功")
          }
        })
      },
      // 验证资料
      changeverifyDoc(e){
        this.saveSelectRows.verifyDoc = e.target.value;
        let data = {}
        data={
          templateId:this.templateId,
          nodeId:this.selectedData.nodeId,
          verifyDoc:this.saveSelectRows.verifyDoc,
        }
        editTemplateNode(data).then((res)=>{
          if(res){
            this.getWbsTemplate()
          }
          if(res.code=='200'){
            this.$message.success("修改成功")
          }
        })
      },
      // 完成标准
      changecompleteStandard(e){
        this.saveSelectRows.completeStandard = e.target.value;
        console.log(this.saveSelectRows.completeStandard)
        let data = {}
        data={
          templateId:this.templateId,
          nodeId:this.selectedData.nodeId,
          completeStandard:this.saveSelectRows.completeStandard,
        }
        editTemplateNode(data).then((res)=>{
          if(res){
            this.getWbsTemplate()
          }
          if(res.code=='200'){
            this.$message.success("修改成功")
          }
        })
      },
      // 管控节点
      changeLevel(value){
        console.log(this.selectedData)
        let data={}
        data={
          templateId:this.templateId,
          nodeId:this.selectedData.nodeId,
          controlLevelId:value
        }
        editTemplateNode(data).then((res)=>{
          if(res){
            this.getWbsTemplate()
          }
          if(res.code=='200'){
            this.$message.success("修改成功")
          }
        })
      },
      // 时间标准
      changedateStandard(value){
        console.log(this.selectedData)
        let data={}
        data={
          templateId:this.templateId,
          nodeId:this.selectedData.nodeId,
          dateStandard:value
        }
        editTemplateNode(data).then((res)=>{
          if(res){
            this.getWbsTemplate()
          }
          if(res.code=='200'){
            this.$message.success("修改成功")
          }
        })
      },
      // 业务事项
      onCellChangeBusiness(val){
        console.log("阶段名称：",val)
        this.selectedData.name = val
      },
      // 获取模板
      getWbsTemplate(){
        getWbsTemplate(this.templateId).then((res)=>{
          console.log(res)
          this.tableData = []
          this.tableData = res.data.wbsNodeList
          console.log(this.tableData)
          const tasks = gantt.getTaskByTime()
          console.log(tasks)
          const tree  = this.dataListToTree(this.tableData)
          console.log(tree)
          const dataList = this.resetDataId(tree)
          console.log(dataList)
          dataList.forEach(data => {
            console.log(data)
            // if (data.workPackId) {
            //   const parentNames = data.parentNames.split('{|}')
            //   parentNames.some(name => {
            //     return tasks.some(task => {
            //       console.log(task)
            //       if (task.name === name) {
            //         data.workPackId = task.id
            //         task.$open = true;
            //         gantt.updateTask(task.id)
            //         const childLength = gantt.getChildren(task.id).length
            //         data.index = childLength + 1
            //         if (!data.start_date) {
            //           data.start_date = new Date()
            //         }
            //         return true
            //       }
            //     })
            //   })
            // }
            gantt.addTask(this.valuesToTask(data), data.parent, data.index || 1)
          })
          const allTasks = gantt.getTaskByTime()
          console.log(allTasks)
          console.log(this.tableData )

          this.tableData = this.dataListToTree(allTasks)
          console.log(this.tableData)
        })
      },
      // 保存阶段名称
      blurData(e,record){
        console.log(record)
        this.saveSelectRows.name = e.target.value;
        console.log(this.saveSelectRows.name)
        let data = {}
        if(this.selectedData.nodeLevel==1 ||this.selectedData.nodeLevel==2){
          data={
            templateId:this.templateId,
            nodeId:this.selectedData.nodeId,
            parentId:this.selectedData.workPackId,
            workPackName:this.saveSelectRows.name,

          }
        }else{
          data={
            templateId:this.templateId,
            nodeId:this.selectedData.nodeId,
            // parentId:this.selectedData.workPackId,
            name:this.saveSelectRows.name,
          }
        }
        editTemplateNode(data).then((res)=>{
          if(res){
            this.getWbsTemplate()
          }
          if(res.code=='200'){
            this.$message.success("修改成功")
          }
        })
      },
      handleChange(e) {
        const value = e.target.value;
        this.value = value;
        console.log(value)
      },
      // 模糊搜索
      handleSearch(value) {
        let result;
        if (!value || value.indexOf('@') >= 0) {
          result = [];
        } else {
          result = ['gmail.com', '163.com', 'qq.com'].map(domain => `${value}@${domain}`);
        }
        this.emailList = result
      },
      handleSelectChange(value) {
        console.log(value);
        if(value==1){
          this.levelOption= 1
        }else if (value==2){
          this.levelOption=2
        }
        console.log(this.levelOption)
        this.form.setFieldsValue({
          note: value,
        });
      },
      // 点击行
      clickRow(record, index){
        return {
          on: {
            click: () => {
              this.selectId = record.nodeId
              this.selectedData = record
              console.log(this.selectedData)
              this.rowClassNames(record)
              gantt.selectTask(record.nodeId);
            }
          }
        }
      },
      onCellChange(key, dataIndex, value) {
        console.log(`${dataIndex}：${value} `);
        const dataSource = [...this.dataSource];
        const target = dataSource.find(item => item.key === key);
        if (target) {
          target[dataIndex] = value;
          this.dataSource = dataSource;
        }
      },
      onCellChangeDur(record, dataIndex, value){
        console.log(record)
        console.log(dataIndex)
        console.log(value)

        const start = record.start_date
        const endDate = gantt.calculateEndDate({
          start_date: start,
          duration: value
        })
        this.form.setFieldsValue({
          period:start.toDate()
        })


        const dataSource = [...this.dataSource];
        const target = dataSource.find(item => item.key === key);
        if (target) {
          target[dataIndex] = value;
          this.dataSource = dataSource;
        }
      },
      onClose(){
        this.visible=false
      },
      showDrawer() {
        this.visible = true;
      },
      afterVisibleChange(visible){
        if(visible){
          gantt.refreshData()
        }
      },
      getChildrenSize(p){
        let size = 0
        const getChildSize = (p)=>{
          if(p.type==='task'){
            return
          }
          p.children.forEach(c => {
            if(c.type==='task'){
              size++
            }
            getChildSize(c)
          })
        }
        getChildSize(p)
        return size
      },
      getColumns() {
        let rowIndex = 1
        return [
          {
            title: '编号',
            width: 60,
            fixed:'left',
            customRender: () => {
              return rowIndex++
            }
          },
          {
            title: '阶段/类别',
            dataIndex: 'name',
            scopedSlots: { customRender: 'name' },
            width: 300,
            // customRender: (n,row) => {
            //   if(row.type!=='task'){
            //     return row.name
            //   }else{
            //     return ''
            //   }
            // }
          },
          {
            title: '业务事项',
            dataIndex: 'businessMatters',
            width: 120,
            // customRender: (n,row) => {
            //   if(row.type!=='task'){
            //     const size = this.getChildrenSize(row)
            //     return `${size}个`
            //   }else{
            //     return row.matters
            //   }
            // },
            scopedSlots: { customRender: 'businessMatters' },
          },
          {
            title: '管控级别',
            dataIndex: 'level',
            scopedSlots: { customRender: 'level' },
            width: 120,
          },
          {
            title: '周期',
            dataIndex: 'duration',
            width: 120,
            scopedSlots: { customRender: 'duration' },
          },
          {
            title: '时间标准',
            dataIndex: 'dateStandard',
            scopedSlots: { customRender: 'dateStandard' },
            width: 120,
          },
          {
            title: '标准开始时间',
            dataIndex: 'startDate',
            scopedSlots: { customRender: 'startDate' },
            width: 120
          },
          {
            title: '标准完成时间',
            dataIndex: 'completeDate',
            scopedSlots: { customRender: 'completeDate' },
            width: 120
          },
          {
            title: '完成标准',
            dataIndex: 'completeStandard',
            scopedSlots: { customRender: 'completeStandard' },
            width: 120,
            ellipsis: true
          },
          {
            title: '验证资料',
            dataIndex: 'verifyDoc',
            width: 120,
            scopedSlots: { customRender: 'verifyDoc' },
            ellipsis: true
          },
          {
            title: '第一责任人',
            width: 120,
            dataIndex: 'firstResponsible',
            scopedSlots: { customRender: 'firstResponsible' },
            ellipsis: true,
            fixed:'right'
          },
          // {
          //   title: '直接责任人',
          //   dataIndex: 'responsible',
          //   scopedSlots: { customRender: 'responsible' },
          //   ellipsis: true
          // },
        ]
      },
      rowExpand(expanded, task){
        console.log(task)
        if(expanded){
          gantt.open(task.id)
        }else{
          gantt.close(task.id)
        }
      },
      getRowSelection() {
        return {
          columnWidth:40,
          type:'radio',
          onChange: (selectedRowKeys, selectedRows) => {
            this.selectedData = selectedRows
            console.log(this.selectedData)
            gantt.selectTask(this.selectedData.nodeId);
          },
          onSelect: (record, selected, selectedRows) => {
            this.selectedData = selectedRows
            console.log(this.selectedData)
            this.selectLevel= this.selectedData.levelType
            console.log(this.selectLevel)
            gantt.selectTask(this.selectedData.nodeId);
          },
          onSelectAll: (selected, selectedRows, changeRows) => {
            this.selectedData = selectedRows
            console.log("onSelectAll"+this.selectedData)
            gantt.selectTask(this.selectedData.nodeId);
          }
        }
      },
      dataListToTree(){
        let dataList = this.tableData
        console.log(dataList)
        const dataMaps = {}
        const tree = []
        const dataListCopy = []
        dataList.forEach(data => {
          console.log(data)
          const copy = { ...data, start_date: data.startDate,parent:data.parent ,children:data.children}
          // copy.children = []
          console.log(copy.id)
          dataMaps[copy.id] = copy
          dataListCopy.push(copy)
        })
        dataListCopy.forEach(data => {
          if (data.parent) {
            const parent = dataMaps[data.parent]
            if (parent) {
              parent.children.push(data)
            } else {
              data.parent = null
              tree.push(data)
            }
          } else {
            tree.push(data)
          }
        })
        console.log(tree)
        return tree
      },
      resetDataId(tree) {
        console.log(tree)
        let index = 1
        const resetIdDataList = []
        const readTree = (children, parent) => {
          console.log(children)
          children.forEach(child => {
            console.log(child)
            index++
            if (parent) {
              child.parent = parent
            }
            console.log(child)
            if(child.children){
              if (child.children.length > 0) {
                child.id = `${new Date().getTime() + index}`
                console.log(children.id)
                resetIdDataList.push(child)
                console.log(resetIdDataList)
                readTree(child.children, child.id)
              } else {
                child.id = `${new Date().getTime() + index}`
                resetIdDataList.push(child)
              }
            }
          })
        }
        console.log(readTree)
        readTree(tree, 0)
        return resetIdDataList
      },
      onTemplateDataImport(dataList) {
        const tasks = gantt.getTaskByTime()
        const tree  = this.dataListToTree(dataList)
        dataList = this.resetDataId(tree)
        dataList.forEach(data => {
          // if (data.parentNames) {
          //   const parentNames = data.parentNames.split('{|}')
          //   parentNames.some(name => {
          //     return tasks.some(task => {
          //       if (task.name === name) {
          //         data.parent = task.id
          //         task.$open = true;
          //         gantt.updateTask(task.id)
          //         const childLength = gantt.getChildren(task.id).length
          //         data.index = childLength + 1
          //         if (!data.start_date) {
          //           data.start_date = new Date()
          //         }
          //         return true
          //       }
          //     })
          //   })
          // }
          gantt.addTask(this.valuesToTask(data), data.parent, data.index || 1)
        })
        const allTasks = gantt.getTaskByTime()
        this.tableData = this.dataListToTree(allTasks)
      },
      importFromTemplate() {
        console.log(this.selectLevel)
        // if(this.selectedData.length==0){
        //   this.$confirm({
        //     title: '提示！！',
        //     content: '请选中任务',
        //     okText: '确定',
        //     cancelText: '取消',
        //     onOk() {
        //       return false
        //     },
        //     onCancel() {
        //       return false
        //     },
        //   });

        // }
        this.taskTemplateVisible = true
      },
      importFromTemplateHide() {
        this.taskTemplateVisible = false
      },
      parentFilterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        )
      },
      onTaskTypeChange(val) {
        this.taskType = val
      },
      onChange(value, dateString) {
        const start = value[0]
        console.log(start.toDate())
        const end = value[1]
        const duration = gantt.calculateDuration({
          start_date: start.toDate(),
          end_date: end.toDate()
        })
        this.form.setFieldsValue({
          duration
        })
      },
      onDaySizeChange(value) {
        const start = this.startDates[0]
        const endDate = gantt.calculateEndDate({
          start_date: start.toDate(),
          duration: value
        })
        this.form.setFieldsValue({
          period:start.toDate()
        })
      },
      getPeriod(){
        this.startDates = this.form.getFieldValue('period')
      },
      handleCancel() {
        this.confirmLoading = false
        this.addVisible = false
      },
      valuesToTask(values) {
        console.log(values)
        return {
          id: values.id,
          parent:values.parent,
          text: values.matters||values.name,
          name: values.name,
          start_date: values.start_date,
          startDate:values.startDate||'',
          end_date:values.end_date,
          endDate:values.endDate||'',
          duration: values.duration,
          parentId: values.workPackId,
          type: values.type,
          preTask: values.preTask,
          matters: values.businessMatters,
          level: values.level,
          levelType: values.levelType,
          responsible: values.responsible,
          firstResponsible: values.firstResponsible,
          nodeLevel:values.nodeLevel,
          nodeId:values.nodeId,
          workPackId:values.workPackId
        }
      },
      handleSubmit() {
        // console.log(this.valuesToTask((values)))
        this.confirmLoading = true
        // var taskId = gantt.addTask({
        //     id:10,
        //     text:"Task #5",
        //     start_date:"02-09-2013",
        //     duration:28
        // }, "project_2", 1);
        this.form.validateFields((err, values) => {
          console.log(this.selectedData)
          if (!err) {
            console.log(values)
            this.addVisible = false
            const start = this.selectedData.start_date
            const duration = this.selectedData.duration
            const end = this.selectedData.start_date
            const parent = this.selectedData.parent
            values.start_date = start
            values.duration = duration
            values.text = ' '
            // if (values.id) {
            //   const task = gantt.getTask(values.id)
            //   const vtt = this.valuesToTask(values)
            //   const taskUpdate = {...task,...vtt}
            //   gantt.updateTask(values.id, taskUpdate)
            // } else {

            console.log(this.levelOption)
            let data = {}
            //新增同级节点
            if(this.levelOption===1){
              //如果选择的是一级节点
              console.log(this.selectedData.nodeLevel)
              if(this.selectedData.nodeLevel=='1'){
                // values.id = `${new Date().getTime()}`
                // console.log(values.id)
                // gantt.addTask(this.valuesToTask(values), parent)
                addSameNode({templateId:this.templateId,workPackId:this.selectedData.workPackId}).then((res)=>{
                  if(res){
                    this.getWbsTemplate()
                  }
                  if(res.code=='200'){
                    this.$message.success("新增节点成功")
                    this.resultData = res.data
                  }
                })
                // values.id = `${new Date().getTime()}`

                // console.log(values.id)
                // gantt.addTask(this.valuesToTask(values), parent)
                //如果选择的是二级节点

              } else if(this.selectedData.nodeLevel=='2'){
                // values.id = `${new Date().getTime()}`
                // console.log(values.id)
                // gantt.addTask(this.valuesToTask(values), parent)
                addSameNode({templateId:this.templateId,parentId:this.selectedData.nodeId}).then((res)=>{

                  if(res){
                    this.getWbsTemplate()
                  }
                  if(res.code=='200'){
                    this.$message.success("新增成功")
                  }
                })
                // values.id = `${new Date().getTime()}`
                // console.log(values.id)
                // gantt.addTask(this.valuesToTask(values), parent)
              }else{
                // values.id = `${new Date().getTime()}`
                // console.log(values.id)
                // gantt.addTask(this.valuesToTask(values), parent)
                addSameNode({
                  parentId:this.selectedData.workPackId,
                  templateId:this.templateId,
                  id:this.selectedData.nodeId}).then((res)=>{
                  if(res){
                    this.getWbsTemplate()
                  }
                  if(res.code=='200'){
                    this.$message.success("新增成功")
                  }
                })
              }
              // else if(this.selectedData[0].nodeLevel==undefined){
              //   this.selectedData[0].nodeLevel=data.level
              //   this.selectedData[0].parentId = data.workPackId
              //   this.selectedData[0].nodeId = data.id
              //   if(this.selectedData[0].nodeLevel=='1'){
              //     addSameNode({templateId:this.templateId}).then((res)=>{
              //       if(res.code=='200'){
              //         this.$message.success("新增节点成功")
              //         data = res.data
              //       }
              //     })
              //     values.id = `${new Date().getTime()}`
              //     console.log(values.id)
              //     gantt.addTask(this.valuesToTask(values), parent)
              //     //如果选择的是二级节点
              //
              //   } else if(this.selectedData[0].nodeLevel=='2'){
              //     addSameNode({parentId:this.selectedData[0].parentId,templateId:this.templateId})
              //     values.id = `${new Date().getTime()}`
              //     console.log(values.id)
              //     gantt.addTask(this.valuesToTask(values), parent)
              //     // this.getWbsTemplate()
              //   }else if(this.selectedData[0].nodeLevel=='3'){
              //     addSameNode({parentId:this.selectedData[0].parentId,templateId:this.templateId,id:this.selectedData[0].id}).then((res)=>{
              //       if(res.code=='200'){
              //         this.$message.success("新增成功")
              //       }
              //     })
              //     values.id = `${new Date().getTime()}`
              //     console.log(values.id)
              //     gantt.addTask(this.valuesToTask(values), parent)
              //     // this.getWbsTemplate()
              //   }
              // }
            }


            else if(this.levelOption===2){
              // 新增下级节点
              let list ={}
              if(this.selectedData.nodeLevel=='1' || this.selectedData.nodeLevel=='2' ){
                addNextNode({id:this.selectedData.nodeId,templateId:this.templateId}).then((res)=>{
                  if(res){
                    this.getWbsTemplate()
                  }
                  if(res.code=='200'){
                    this.$message.success("新增成功")
                    list = res.data
                  }
                })
                values.id = `${new Date().getTime()}`
                console.log(values)
                // gantt.addTask(this.valuesToTask(values),  this.selectedData.nodeId)
              }else{
                this.$message.error("此节点不可新增下级节点")
              }
              // if(this.selectedData[0].nodeLevel==undefined){
              //   this.selectedData[0].nodeLevel=list.level
              //   this.selectedData[0].nodeId = list.id
              //   if(this.selectedData[0].nodeLevel=='1' || this.selectedData[0].nodeLevel=='2' ){
              //     addNextNode({id:this.selectedData[0].nodeId,templateId:this.templateId}).then((res)=>{
              //       if(res.code=='200'){
              //         this.$message.success("新增成功")
              //       }
              //     })
              //     values.id = `${new Date().getTime()}`
              //     console.log(values.id)
              //     gantt.addTask(this.valuesToTask(values),  this.selectedData[0].id)
              // this.getWbsTemplate()
              //   }
              // }
            }
            const allTasks = gantt.getTaskByTime()
            this.tableData = this.dataListToTree(allTasks)
            // }
            //前置任务
            // const links = gantt.getLinks()
            // links.forEach(link => {
            //   if (values.preTask.indexOf(link.source) !== -1 && link.target === values.id) {
            //     gantt.deleteLink(link.id)
            //   }
            // })
            // values.preTask.forEach(pre => {
            //   gantt.addLink({
            //     id: `${new Date().getTime()}`,
            //     source: pre,
            //     target: values.id,
            //     type: gantt.config.links.finish_to_start
            //   })
            // })
          }
        })
      },
      action(name) {
        // if('moveUp'===name){
        //   let _this = this
        //   let task_id = gantt.getSelectedId()
        //     _this.$refs.ganttCom.action(name)
        // }

        // 升级
        if('outdent'===name){
          let data={}
          if(this.selectedData.nodeLevel==1 || this.selectedData.nodeLevel==2){
            data ={
              templateId:this.templateId,
              positionTypeEnum:2,
              workPackId:this.selectedData.nodeId,
            }
          }else{
            data = {
              templateId:this.templateId,
              positionTypeEnum:2,
              workId:this.selectedData.nodeId,
            }
          }
          editNode(data).then((res)=>{
            if(res){
              this.getWbsTemplate()
            }
            if(res.code=='200'){
              this.$message.success("升级成功")
            }
          })
        }

        // 降级
        if('indentdent'===name){
          let data={}
          if(this.selectedData.nodeLevel==1 || this.selectedData.nodeLevel==2){
            data ={
              templateId:this.templateId,
              positionTypeEnum:3,
              workPackId:this.selectedData.nodeId,
            }
          }else{
            data = {
              templateId:this.templateId,
              positionTypeEnum:3,
              workId:this.selectedData.nodeId,
            }
          }
          editNode(data).then((res)=>{
            if(res.code=='200'){
              this.$message.success("升级成功")
            }
          })
        }

        // 上移
        if('moveUp'===name){
          let data={}
          if(this.selectedData.nodeLevel==1 || this.selectedData.nodeLevel==2){
            data ={
              templateId:this.templateId,
              positionTypeEnum:0,
              workPackId:this.selectedData.nodeId,
            }
          }else{
            data = {
              templateId:this.templateId,
              positionTypeEnum:0,
              workId:this.selectedData.nodeId,
            }
          }
          editNode(data).then((res)=>{
            if(res){
              this.getWbsTemplate()
            }
            if(res.code=='200'){
              this.$message.success("升级成功")
            }
          })
        }

        // 下移
        if('moveDown'===name){
          let data={}
          if(this.selectedData.nodeLevel==1 || this.selectedData.nodeLevel==2){
            data ={
              templateId:this.templateId,
              positionTypeEnum:1,
              workPackId:this.selectedData.nodeId,
            }
          }else{
            data = {
              templateId:this.templateId,
              positionTypeEnum:1,
              workId:this.selectedData.nodeId,
            }
          }
          editNode(data).then((res)=>{
            if(res){
              this.getWbsTemplate()
            }
            if(res.code=='200'){
              this.$message.success("升级成功")
            }
          })
        }

        // 删除节点
        if ('del' === name) {
          let task_id = gantt.getSelectedId()
          if (!task_id) {
            this.$message.warn('请先选择要删除的节点')
            return
          }
          let _this = this
          this.$confirm({
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            title: '删除当前选择的节点?',
            onOk() {
              let data = {}
              if(_this.selectedData.nodeLevel==1 || _this.selectedData.nodeLevel==2){
                data ={
                  workPackId:_this.selectedData.nodeId,
                  templateId:_this.templateId,
                }
              }else{
                data = {
                  templateId:_this.templateId,
                  parentId:_this.selectedData.workPackId,
                  id:_this.selectedData.nodeId,
                }
              }
              deleteNode(data).then((res)=>{
                if(res){
                  this.getWbsTemplate()
                }
                if(res.code=='200'){
                  this.$message.success("节点删除成功")
                }
              })
              // _this.$refs.ganttCom.action(name)
            },
            onCancel() {
              console.log('Cancel');
            },
            class: 'test',
          });
          // this.$confirm({
          //   okText: '删除',
          //   okType: 'danger',
          //   cancelText: '取消',
          //   title: '删除当前选择的节点?',
          //   onOk() {
          //       let data = {}
          // if(_this.selectedData.nodeLevel==1 || _this.selectedData.nodeLevel==2){
          //   data ={
          //     id:_this.selectedData.nodeId,
          //   }
          // }else{
          //   data = {
          //     templateId:_this.templateId,
          //     parentId:_this.selectedData.parentId,
          //     id:_this.selectedData.nodeId,
          //   }
          // }
          // deleteNode(data).then((res)=>{
          //   if(res.code=='200'){
          //     this.$message.success("节点删除成功")
          //   }
          // })
          // _this.$refs.ganttCom.action(name)
          // return false
          // },
          //   onCancel() {
          //   },
          //   class: 'test'
          // })
        } else {
          this.$refs.ganttCom.action(name)
        }
        const allTasks = gantt.getTaskByTime()
        console.log(allTasks)
        this.tableData = this.dataListToTree(allTasks)
        console.log(this.tableData)
      },
      exportToPDFs() {
        gantt.exportToPDF({
          name: 'mygantt.pdf',
          header: '<h1>My company</h1>',
          footer: '<h4>Bottom line</h4>',
          locale: 'en',
          start: '01-04-2013',
          end: '11-04-2013',
          skin: 'terrace',
          data: {}
        })
      },
      addModal(task) {
        console.log(this.selectedTask)
        // if(this.selectedTask==null){
        //   this.$confirm({
        //     title: '提示！！',
        //     content: '请选中任务',
        //     okText: '确定',
        //     cancelText: '取消',
        //     onOk() {
        //       return false
        //     },
        //     onCancel() {
        //       return false
        //     },
        //   });
        //   return false
        // }
        this.confirmLoading = false
        const tasks = gantt.getTaskByTime()
        let parent = gantt.getSelectedId()

        // if(this.selectedTask.levelType==4){
        //   this.addvisible4 = true
        // }
        // if (task) {
        //   if (task.id) {
        //     this.preTasks = tasks.filter(t => t.id !== task.id)
        //     this.modalTitle = '编辑节点'
        //   } else {
        //     this.preTasks = tasks
        //     this.modalTitle = '新增节点'
        //   }
        //   this.form = this.$form.createForm(this, {})
        //   parent = task.parent
        // } else {
        //   this.preTasks = tasks
        //   this.modalTitle = '新增节点'
        //   this.form = this.$form.createForm(this, {})
        // }
        this.addVisible = true
        // if (task) {
        //   console.log(task)
        //   this.$nextTick(() => {
        //     this.taskType = task.type
        //     const period = [moment(task.start_date), moment(task.end_date)]
        //     this.form.setFieldsValue({
        //       id: task.id,
        //       name: task.name,
        //       period,
        //       level: task.level,
        //       type: task.type,
        //       duration: task.duration,
        //       parent: task.parent ? task.parent : ''
        //     })
        //   })
        // } else if (parent) {


        console.log(parent)
        // this.taskType = 'task'
        // this.$nextTick(() => {
        //   setTimeout(()=>{
        //     this.form.setFieldsValue({
        //       parent,
        //       type: 'task'
        //     })
        //   },0)
        // })
        // }
      },

      selectTask: function(task) {
        console.log('当前选中行数据:', task)
        this.selectedTask = task
        // gantt.selectTask(task.id);
      },
      deleteTask: function(taskId) {
        console.log('当前删除的数据：', taskId)
        this.selectedTask = task
        gantt.deleteTask(task.id);
      },
      addMessage(message) {
        let _this = this
        _this.messages.unshift(message)
        if (_this.messages.length > 40) {
          _this.messages.pop()
        }
      },
      logTaskUpdate(id, mode, task) {
        const text = (task && task.text ? ` (${task.text})` : '')
        const message = `Task ${mode}: ${id} ${text}`
        this.addMessage(message)
      },
      rowClassNames(record){
        if( this.selectId == record.nodeId ){
          return 'clickRowStyle'
        }
      },
      logLinkUpdate(id, mode, link) {
        let message = `Link ${mode}: ${id}`
        if (link) {
          message += ` ( source: ${link.source}, target: ${link.target} )`
        }
        this.addMessage(message)
      }
    }
  }
</script>

<style scoped>
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
  /deep/ .ant-table-body  .clickRowStyle{
    background-color: rgb(230, 243, 252);
  }
  /deep/ .ant-pro-basicLayout-children-content-wrap{
    flex:1;
  }
  .gantt-layout{
    position: relative;
  }
  /deep/ .ant-table-thead th{
    height: 60px;
    line-height: 60px;
    padding: 0;
  }
  /deep/ .ant-table-placeholder{
    height: 600px;
  }
  /deep/ .gantt-layout .ant-table-body{
    min-height: 600px;
  }
  /deep/ .ant-drawer-content-wrapper{
    box-shadow: none !important;
  }
  /deep/ .ant-table-selection-column{
    width:40px;
  }
  
  .button-bar {
    margin-bottom: 10px;
  }
  
  .button-bar > button:not(:first-child) {
    margin-left: 10px;
  }
  /deep/ .ant-modal-body{
    padding:0
  }
  /*  /deep/ input[type='text'], input[type='password'], input[type='number'], textarea{*/
  /*      border:none*/
  /*  }*/
  /*  /deep/ .ant-calendar-picker-input.ant-input{*/
  /*      width:130px;*/
  /*      border:none*/
  /*  }*/
  /*/deep/ .ant-select-selection--single{*/
  /*    border:none*/
  /*}*/
  /*/deep/ input{*/
  /*     touch-action: manipulation;*/
  /*     border: none;*/
  /*     width: 70px*/
  /* }*/
  
  td{
    display:flex;
  }
</style>
